import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormDigit,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect,
  ProFormDatePicker,
  ProFormTextArea,
  ProFormGroup,
  ProFormList,
} from '@ant-design/pro-components';
import ProLayout, {
  PageContainer,
  SettingDrawer,
  FooterToolbar,
} from '@ant-design/pro-layout';
import { history } from 'umi';

import { message, TreeSelect, Button, Card, Breadcrumb } from 'antd';
import React, { useRef, useState } from 'react';
import type { ProColumns } from '@ant-design/pro-components';
import {
  EditableProTable,
  ProCard,
  ProFormField,
  ProFormRadio,
} from '@ant-design/pro-components';

type DataSourceType = {
  id: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: string;
  update_at?: string;
  children?: DataSourceType[];
};

const defaultData = [
  {
    id: 624748504,
    工号: 62404,
    title: '人员1',
    readonly: '单位1',
    decs: '身份2',
    state: 'open',
    created_at: '2020-05-26T09:42:56Z',
    update_at: '2020-05-26T09:42:56Z',
  },
  {
    id: 624691229,
    工号: 62404,
    title: '人员2',
    readonly: '单位2',
    decs: '身份2',
    state: 'closed',
    created_at: '2020-05-26T08:19:22Z',
    update_at: '2020-05-26T08:19:22Z',
  },
];

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const formRef = useRef<
    ProFormInstance<{
      name: string;
      company?: string;
      useMode?: string;
    }>
  >();

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>(
    'bottom',
  );
  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '工号',
      dataIndex: '工号',
      // tooltip: '只读，使用form.getFieldValue可以获取到值',
      readonly: true,
      width: '15%',
    },
    {
      title: '人员名称',
      dataIndex: 'title',
      tooltip: '只读，使用form.getFieldValue获取不到值',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
      // 第一行不允许编辑
      editable: (text, record, index) => {
        return index !== 0;
      },
      width: '15%',
    },
    {
      title: '单位',
      dataIndex: 'readonly',
      tooltip: '只读，使用form.getFieldValue可以获取到值',
      readonly: true,
      width: '15%',
    },
    {
      title: '作者次序',
      key: 'state',
      dataIndex: 'state',
      valueType: 'select',
      valueEnum: {
        all: { text: '第一作者', status: 'Default' },
        open: {
          text: '第二作者',
          status: 'Error',
        },
        closed: {
          text: '第三作者',
          status: 'Success',
        },
      },
    },
    {
      title: '参与人员类别',
      key: 'state',
      dataIndex: 'state',
      valueType: 'select',
      valueEnum: {
        all: { text: '类别1', status: 'Default' },
        open: {
          text: '类别2',
          status: 'Error',
        },
        closed: {
          text: '类别3',
          status: 'Success',
        },
      },
    },
    {
      title: '参与人员身份',
      dataIndex: 'decs',
      fieldProps: (from, { rowKey, rowIndex }) => {
        if (from.getFieldValue([rowKey || '', 'title']) === '不好玩') {
          return {
            disabled: true,
          };
        }
        if (rowIndex > 9) {
          return {
            disabled: true,
          };
        }
        return {};
      },
    },
    // {
    //     title: '活动时间',
    //     dataIndex: 'created_at',
    //     valueType: 'date',
    // },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '编辑事务',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>系统管理</Breadcrumb.Item>
            <Breadcrumb.Item>事务管理</Breadcrumb.Item>
            <Breadcrumb.Item>编辑事务</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      extra={[
        <Button
          key="3"
          onClick={() => {
            // console.log(props);
          }}
        >
          操作
        </Button>,
        <Button key="2">操作</Button>,
        <Button
          key="1"
          type="primary"
          onClick={() => {
            history.push('/SystemManage/TransactionManagement');
          }}
        >
          返回
        </Button>,
      ]}
    >
      <Card>
        <ProForm<{
          name: string;
          company?: string;
          useMode?: string;
        }>
          onFinish={async (values) => {
            await waitTime(2000);
            console.log(values);
            const val1 = await formRef.current?.validateFields();
            console.log('validateFields:', val1);
            const val2 =
              await formRef.current?.validateFieldsReturnFormatValue?.();
            console.log('validateFieldsReturnFormatValue:', val2);
            message.success('提交成功');
          }}
          formRef={formRef}
          params={{ id: '100' }}
          formKey="base-form-use-demo"
          dateFormatter={(value, valueType) => {
            console.log('---->', value, valueType);
            return value.format('YYYY/MM/DD HH:mm:ss');
          }}
          request={async () => {
            await waitTime(100);
            return {
              name: '国重实验室',
              useMode: 'chapter',
            };
          }}
          autoFocusFirstInput
          submitter={{
            render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
          }}
          layout={'horizontal'}
        >
          <ProForm.Group>
            <ProFormText
              width="sm"
              name="培养计划名称"
              required
              label="培养计划名称"
            />
            <ProFormSelect
              options={[
                {
                  value: '人群1',
                  label: '人群1',
                },
                {
                  value: '人群2',
                  label: '人群2',
                },
              ]}
              width="sm"
              required
              name="培养计划适用人员"
              label="培养计划适用人员"
            />
            <ProFormTextArea
              width="xl"
              required
              name="培养计划备注"
              label="培养计划备注"
              fieldProps={{
                rows: 6,
              }}
            />
          </ProForm.Group>
          <ProFormList
            name="培养计划自定义条件"
            // label="自定义事务步骤"
            creatorButtonProps={{
              creatorButtonText: '添加事务步骤',
            }}
            min={1}
            copyIconProps={false}
            itemRender={({ listDom, action }, { index }) => (
              <ProCard
                key={index}
                bordered
                style={{ marginBottom: 8 }}
                title={`步骤${index + 1}`}
                extra={action}
                bodyStyle={{ paddingBottom: 0 }}
              >
                {listDom}
              </ProCard>
            )}
            // creatorRecord={{ 小条件数组: [{ 小条件类型: 'SCI分区' }] }}
            // initialValue={[{ name: '颜色', items: [{ name: '红' }, { name: '黄' }] }]}
          >
            <ProForm.Group>
              <ProFormText
                style={{ padding: 0 }}
                width="md"
                name="条件主体"
                label="条件主体"
              />
            </ProForm.Group>
            <ProForm.Item isListField style={{ marginBottom: 0 }}>
              <ProFormList
                name="小条件数组"
                creatorButtonProps={{
                  creatorButtonText: '新建',
                  icon: false,
                  type: 'link',
                  style: { width: 'unset' },
                  position: 'bottom',
                }}
                min={1}
                copyIconProps={false}
                deleteIconProps={{ tooltipText: '删除' }}
                itemRender={({ listDom, action }, { index }) => (
                  <div
                    style={{
                      display: 'inline-flex',
                      marginRight: 20,
                    }}
                    key={index}
                  >
                    {listDom}
                    {action}
                  </div>
                )}
              >
                <ProForm.Group>
                  <ProFormText
                    allowClear={false}
                    width="sm"
                    name={'小条件类型'}
                    label={'小条件类型'}
                  />
                  <ProFormSelect
                    allowClear={false}
                    width="xs"
                    name={'运算符'}
                    label={'运算符'}
                    valueEnum={{
                      '>': '>',
                      '=': '=',
                    }}
                  />
                  <ProFormText
                    allowClear={false}
                    width="sm"
                    name={'小条件数值'}
                    label={'小条件数值'}
                  />
                </ProForm.Group>
              </ProFormList>
            </ProForm.Item>
          </ProFormList>
        </ProForm>
      </Card>
    </PageContainer>
  );
};
